package com.suse.lhw.hms.shiroserver.config;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

/**
 * @ProjectName: health_manage_system
 * @Package: com.suse.lhw.hms.shiroserver.config
 * @ClassName: Authorizing
 * @Description: java类作用描述
 * @Author: 李鸿炜
 * @CreateDate: 2021/1/28 19:09
 * @UpdateUser: 更新者
 * @UpdateDate: 2021/1/28 19:09
 * @UpdateRemark: 更新说明
 * @Version: 1.0
 */
public class Authorizing extends AuthorizingRealm {
    //模拟数据库的数据
    Map<String, String> userMap = new HashMap<>(26);

    {
        userMap.put("Jim", "123123");
        super.setName("myRealm"); //随便设置一下realm的名称
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        String userName = (String) principals.getPrimaryPrincipal();
        //从数据库拉取角色和权限
        Set<String> roles = getRolesByUserName(userName);
        Set<String> permissions = getPermissionsByUserName(userName);
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        simpleAuthorizationInfo.setStringPermissions(permissions);
        simpleAuthorizationInfo.setRoles(roles);
        return simpleAuthorizationInfo;
    }

    private Set<String> getPermissionsByUserName(String username) {
        /**
         * @Author:Hongwei Li
         * @Description:模拟从数据库中获得数据
         * @Date:20:17 2021/1/30
         * @Param:[]
         * @Return:java.util.Set<java.lang.String>
         **/
        Set<String> permission = new HashSet<String>();
        permission.add("user:delete");
        permission.add("user:add");
        return permission;
    }

    private Set<String> getRolesByUserName(String username) {
        Set<String> roles = new HashSet<>();
        roles.add("admin");
        roles.add("user");
        return roles;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //1.从主体传过来的认证信息中，获得用户名
        String userName = (String) token.getPrincipal();

        //2通过用户名到数据库中获取凭证
        String password = getPasswordByUserName(userName);
        if (password == null) {
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo("Jim", password, "myRealm");
        return authenticationInfo;
    }

    /**
     * 模拟从数据库取凭证的过程
     *
     * @param userName
     * @return
     */
    private String getPasswordByUserName(String userName) {
        return userMap.get(userName);
    }
}
